package cn.edu.scnu.user.service;

import cn.edu.scnu.user.mapper.UserMapper;
import com.easymall.common.pojo.User;
import com.easymall.common.utils.MD5Util;
import com.easymall.common.utils.MapperUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisCluster;

import java.util.UUID;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
//    @Autowired
//    private ShardedJedisPool pool;
    @Autowired
    private JedisCluster jedis;

    private final ObjectMapper mapper = MapperUtil.MP;

    public Integer checkUsername(String userName) {
        return userMapper.queryUsername(userName);
    }

    public void userSave(User user) {
        user.setUserId(UUID.randomUUID().toString());
        user.setUserPassword(MD5Util.md5(user.getUserPassword()));
        userMapper.userSave(user);
    }

    public String doLogin(User user) {
        //ShardedJedis jedis = pool.getResource();
        try {
            user.setUserPassword(MD5Util.md5(user.getUserPassword()));
            User existUser = userMapper.queryUserByNameAndPassword(user);
            if (existUser == null) {
                return "";
            } else {
                String ticket = UUID.randomUUID().toString();
                String userJson = mapper.writeValueAsString(existUser);


                if (jedis.llen("user_logined_" + existUser.getUserId()) >= 3) {
                    jedis.lpop("user_logined_" + existUser.getUserId());
                }
                jedis.rpush("user_logined_" + existUser.getUserId(), ticket);

                // more than 30min
                jedis.setex(ticket, 60 * 30, userJson);

                return ticket;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public String queryUserJson(String ticket) {
        //ShardedJedis jedis = pool.getResource();
        String userJson;
        try {
            Long leftTime = jedis.pttl(ticket);
            if (leftTime < 1000 * 60 * 101) {
                jedis.pexpire(ticket, leftTime + 1000 * 60 * 5);
            }
            userJson = jedis.get(ticket);
            return userJson;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

}
